package org.syntaxlisp.core.match;

import org.syntaxlisp.core.utils.EqualsTo;
import lombok.Builder;
import lombok.Data;

import java.util.Objects;

/**
 * @author HuangYijun
 * @data 2023-06-01 17:36
 **/
@Data
@Builder
public class PositionScope implements EqualsTo {

    private int startPosition;

    private int endPosition;

    boolean isInit;

    public PositionScope addScope(PositionScope target) {
        Objects.requireNonNull(target, "addScope target can not be null!");
        if (isInit) {
            startPosition = Math.min(startPosition, target.getStartPosition());
            endPosition   = Math.max(endPosition, target.getEndPosition());
        } else {
            startPosition = target.getStartPosition();
            endPosition   = target.getEndPosition();
            isInit = true;
        }
        return this;
    }

    public PositionScope copy() {
        return PositionScope.builder()
                            .startPosition(startPosition)
                            .endPosition(endPosition)
                            .build();
    }

    public static PositionScope newInstance() {
        return PositionScope.builder()
                            .startPosition(0)
                            .endPosition(0)
                            .isInit(false)
                            .build();
    }

    public String toString () {
        return "POS(" + startPosition + "," + endPosition + ")";
    }

    @Override
    public boolean equalsTo(EqualsTo o) {
        if (!(o instanceof PositionScope)) {
            return false;
        }
        PositionScope vo = (PositionScope) o;
        return vo.isInit == isInit && vo.startPosition == startPosition && vo.endPosition == endPosition;
    }
}
